<template>
  <!-- 全部患者 -->
  <div class="allPatients">
    <div class="allPatient-left-return">
      <div class="patient-search">
        <el-icon><user /></el-icon>搜索患者
      </div>
      <div :class="{'item-active': isPersonActive === p.customerId}" class="person-item"  v-for="p in historyList" :key="p.customerId">
        <div class="avarat">
          <avaratImg :age="p.age" :customerSex="p.customerSex"></avaratImg>
        </div>
        <span class="person-name" @click="handleGoDetails(p)"><a href="javascript:;">{{p.customerName}}</a></span>
        <span>{{p.from ? ('('+p.from+')') : ''}}</span>
        <span
          v-for="icon in p.showRules"
          class="circular-icon p0"
          :key="icon.id"
          :class="{
            'bg-blue': icon.showType === '蓝色',
            'bg-orange': icon.showType === '黄色',
            'bg-red': icon.showType === '红色',
            'bg-green': icon.showType === '绿色',
            'bg-black': icon.showType === '黑色',
            }"
          >{{icon.showLabel}}</span>
          <span class="circular-icon p0 bg-red" v-if="p.hasArrearsOrder" >欠</span>


        <div class="delete-item" @click="handleDelectItem(p.customerId)"><el-icon><delete /></el-icon></div>
        <div class="register-item" @click="handleToRegister(p.customerId)" >
          <abbr title="挂号" style="text-decoration: none; font-weight: bold;">
            <i class="iconfont icon-jinru_huabanfuben"></i>
          </abbr>
        </div>
      </div>
    </div>
    <div class="allPatient-right-content">
      <zsearch v-loading="loading">
        <template #title>
          <span>全部患者</span>
        </template>
        <template #date>
          <el-date-picker
              class="date-1"
              type="date"
              v-model="date"
              value-format="YYYY-MM-DD"
              placeholder="选择日期">
          </el-date-picker>
        </template>
        <template #select>
          <el-input class="input-1" v-model="name" placeholder="请输入内容"></el-input>
        </template>
        <template #btns>
          <!-- <span class="screen" @click="screen">高级筛选<i class="el-icon-ArrowDown"></i></span> -->
          <el-button class="btn-1" @click="hanledSearch">查询</el-button>
          <el-button class="btn-2">导出</el-button>
        </template>
        <template #table>
          <ztable
            :isShow='true'
            :tableData='list'
            :strucs='groupData'
            width="180"
            align="left"
            :height="'100%'"
            :isshowOperation="true"

          >
          <template #default="slotScope">
            <el-button type="text" class="operation" @click="goDetails(slotScope.rowData)">详情</el-button>
            <el-button type="text" class="operation" @click="handleAppoint(slotScope.rowData, slotScope.index)" v-jurisdiction="'customer:subscribe:add'">预约</el-button>
          </template>
          </ztable>
        </template>
        <template #page>
          <zpage
              :currentPage="current"
              :total="total"
              :pageSize="size"
              @handleSizeChange="handleSizeChange"
              @handleCurrentChange="handleCurrentChange"
          ></zpage>
        </template>
      </zsearch>
    </div>
  </div>

    <!-- 高级搜索 -->
    <zdialog @handleClose="close" v-model="dialogVisible" :btnData="btnData1" title="高级搜索">
      <template #body>
        <div class="screen-body">
            <div class="screen-left">
              <div :class="{'active': isActive === 'person'}" @click="getPerson('person')">个人信息</div>
              <div :class="{'active': isActive === 'seedoctor'}" @click="getSeeDoctor('seedoctor')">就诊信息</div>
            </div>
            <div class="screen-right">
              <div v-if="isActive === 'person'" class="flexwrap">
                <div class="search-info">
                  <div class="lable">姓名</div>
                  <div class="weight">
                    <el-input placeholder="请输入姓名" class="input-7" ></el-input>
                  </div>
                </div>
                <div class="search-info">
                  <div class="lable">病历号</div>
                  <div class="weight">
                    <el-input placeholder="请输入病历号" class="input-7" ></el-input>
                  </div>
                </div>
                <div class="search-info">
                  <div class="lable">电话</div>
                  <div class="weight">
                    <el-input placeholder="请输入电话" class="input-7" ></el-input>
                  </div>
                </div>
                <div class="search-info">
                  <div class="lable pb">病患来源</div>
                  <div class="weight">
                    <el-select class="select-3"  placeholder="请选择病患来源">
                      <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                      </el-option>
                    </el-select>
                  </div>
                </div>
                <div class="search-info">
                  <div class="lable pb">患者标签</div>
                  <div class="weight">
                    <el-select class="select-3"  placeholder="请选择患者标签">
                      <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                      </el-option>
                    </el-select>
                  </div>
                </div>
                <div class="search-info">
                  <div class="lable pb">患者类型</div>
                  <div class="weight">
                    <el-select class="select-3" placeholder="请选择患者类型">
                      <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                      </el-option>
                    </el-select>
                  </div>
                </div>

                <div class="search-info">
                  <div class="lable">省市区</div>
                  <div class="weight">
                    <el-cascader
                      class="cascader-1"
                      :options="options"
                      ></el-cascader>
                  </div>
                </div>
                <div class="search-info">
                  <div class="lable">详细地址</div>
                  <div class="weight">
                    <el-input placeholder="请输入详细地址" class="input-7" ></el-input>
                  </div>
                </div>
                <div class="search-info">
                  <div class="lable pb">会员类型</div>
                  <div class="weight">
                    <el-select class="select-3" placeholder="请选择会员类型">
                      <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                      </el-option>
                    </el-select>
                  </div>
                </div>
                <div class="search-info">
                  <div class="lable pb">性别</div>
                  <div class="weight">
                    <el-select class="select-3" placeholder="请选择性别">
                      <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                      </el-option>
                    </el-select>
                  </div>
                </div>
                <div class="search-info">
                  <div class="lable">年龄</div>
                  <div class="weight f-a">
                    <el-input placeholder="请输入" class="input-8" ></el-input>~
                    <el-input placeholder="请输入" class="input-8" ></el-input>
                  </div>
                </div>
                <div class="search-info">
                  <div class="lable">患者职业</div>
                  <div class="weight">
                    <el-input placeholder="请输入电话" class="input-7" ></el-input>
                  </div>
                </div>
                <div class="search-info">
                  <div class="lable pb">患者备注</div>
                  <div class="weight">
                    <el-input placeholder="请输入备注" class="input-9" type="textarea" ></el-input>
                  </div>
                </div>
              </div>
              <div v-if="isActive === 'seedoctor'" class="flexwrap">
                <div class="search-info">
                  <div class="lable">初诊医生</div>
                  <div class="weight">
                    <el-input placeholder="请输入姓名" class="input-7" ></el-input>
                  </div>
                </div>
                <div class="search-info">
                  <div class="lable">初诊日期</div>
                  <div class="weight f-a" >
                    <el-date-picker
                      class="date-4"

                      type="date"
                      placeholder="开始日期">
                    </el-date-picker>~
                    <el-date-picker
                      class="date-4"

                      type="date"
                      placeholder="结束日期">
                    </el-date-picker>
                  </div>
                </div>
                <div class="search-info">
                  <div class="lable">上次就诊医生</div>
                  <div class="weight">
                    <el-input placeholder="请输入姓名" class="input-7" ></el-input>
                  </div>
                </div>
                <div class="search-info">
                  <div class="lable">上次就诊日期</div>
                  <div class="weight f-a" >
                    <el-date-picker
                      class="date-4"

                      type="date"
                      placeholder="选择日期">
                    </el-date-picker>~
                    <el-date-picker
                      class="date-4"

                      type="date"
                      placeholder="选择日期">
                    </el-date-picker>
                  </div>
                </div>
                <div class="search-info">
                  <div class="lable">欠费金额</div>
                  <div class="weight f-a">
                    <el-input placeholder="请输入" class="input-8" ></el-input>~
                    <el-input placeholder="请输入" class="input-8" ></el-input>
                  </div>
                </div>
                <div class="search-info">
                  <div class="lable">消费金额</div>
                  <div class="weight f-a">
                    <el-input placeholder="请输入" class="input-8"></el-input>~
                    <el-input placeholder="请输入" class="input-8" ></el-input>
                  </div>
                </div>
              </div>
            </div>
        </div>
      </template>
    </zdialog>

    <!-- 预约 -->
    <el-drawer
			size="42%"
			:title="title"
			v-model="showDrawer"
			:before-close="drawerClose" destroy-on-close>
      <zaddpatient
            @cancel="cancel"
            @saveMakeAnAppointment="saveMakeAnAppointment"
            @saveAndRegister="saveAndRegister"
            v-if="isADD === 'add'"
      ></zaddpatient>
      <zregister v-if="isADD === 'register'"
          @cancel="cancel"
          :userId="PersonId"
      ></zregister>
      <zmakeanapp
        v-if="isADD === 'makeanapp'"
        @handlebtn="handlebtn"
        @cancel="cancel"
        :personName="personName"
        :personId="personId"
      ></zmakeanapp>
    </el-drawer>
</template>

<script lang='ts'>
import { User, Delete} from '@element-plus/icons-vue'
import ztable from '@components/Table/index.vue'
import zpage from '@components/pagination/pagination.vue'
import zsearch from '@components/search/search.vue'
import zdialog from '@components/dialog/dialog.vue'
import { defineComponent, reactive, toRefs, onUnmounted, ref } from 'vue'
import useConfgin from '../../hook/getconfig'
import { debounce } from "../../utils/debounce"

import zmakeanapp from "../../components/patient/makeAnAppointment.vue"
import zaddpatient from "../../components/patient/add.vue"
import zregister from "../../components/patient/register.vue"

import avaratImg from "../../components/avatarImg/avatarImg.vue"

import useRequet, { RespData } from "../../hook/network"

import useDataCheck, { DataStruc } from "../../hook/datastruc";
import { ElMessage, ElMessageBox } from 'element-plus'

// 详情添加患者
import useSetAddLog from "../../hook/setAddLog"

import { useRouter } from "vue-router"
import { HistoryList } from "../../types/index"
import { getBirthDay } from "../../usefn/getBirthday"

type OPtions = {
  value: string,
  label: string
}
const ID = 518
export default defineComponent({
  name: 'AllPatients',
  components: {
    ztable,
    zpage,
    zsearch,
    zdialog,

    avaratImg,

    zmakeanapp,
    zaddpatient,
    zregister,

    User, Delete
  },
  setup() {
    let search = reactive({
      date:'',
      name:'',
      current: 1,
      size: 10,
      total: 0,
      list: [],
      dialogVisible: false,
      isActive: 'person',
      isPersonActive: -1,

      loading: false,
      personName: '',
      personId: null as any,
    })

    const advancedSearch = reactive({
      options:[] as OPtions[]
    })
    const {groupData, groupDataAdd, groupDataUpdate} = useConfgin(ID)
    const router = useRouter()
    const request = useRequet({ path: "" });
    const req = () => {
      search.loading = true
      request.sendRequest({
        address: 'customer/info/getCustomerPage',
        params: search || {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取全部患者失败')
					search.list = resp.data.records
          search.list.forEach((i:any) => {
            i.birthDate = (i.birthDate && getBirthDay(i.birthDate)) || '暂无'
          })
          search.total = resp.data.total
          search.current = resp.data.current

          search.loading = false
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取全部患者失败')
          search.loading = false
        },
        method: "POST",
      })
      search.loading = false
    }
    req()


    // 详情
    const goDetails = (rowData: any) => {
      console.log('详情', rowData)
      let id = rowData.id
      router.push(`/allPatientDetails/${id}/patient`)
      useSetAddLog(id)
      getHistoryList()
    }

    // 预约
    const handleAppoint = (rowData: any, index: number) => {
      console.log('预约', rowData, index)
      search.personName = rowData.name;
      search.personId = rowData.id;

      isADD.value = 'makeanapp'
      showDrawer.value = true
    }
    const btnData1 = [
      {
        name: '取消',
        func: (data: boolean) => {
          console.log('取消', data)
          search.dialogVisible = data
        }
      },
      {
        name: '保存',
        func: (data: object) => {
          console.log('保存', data)
          ElMessage('功能还在完善,敬请期待......');
        }
      },
    ]

    const debounceRefresh = debounce(req, 1000)
    const hanledSearch = () => {
      console.debug('搜索')
      debounceRefresh()
    }
     // 分页
    const handleCurrentChange = (val: number) => {
			search.current = val
      req()
			console.debug('handleCurrentChange', val)
		}
    const handleSizeChange = (val: number) => {
      search.size = val
      req()
			console.debug('handleSizeChange', val)
		}

    const historyList = ref([] as HistoryList[])
    // 获取历史患者
    const getHistoryList = () => {
      request.sendRequest({
        address: 'customer/info/getSelectLogPage',
        params: {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error('获取历史患者' + resp.msg )
					historyList.value = resp.data.records

          // window.localStorage.setItem('historyList', JSON.stringify(historyList.value))
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error('获取历史患者' + resp.msg )

        },
        method: "POST",
      })
    }
    getHistoryList()


    // 跳转详情
    const handleGoDetails = (Data: HistoryList) => {
      search.isPersonActive = Data.customerId
      let id = Data.customerId
      console.time('执行时间')
      router.push(`/allPatientDetails/${id}/patient`)
      console.timeEnd('执行时间')
    }

    const handleDelectItem = (id: number) => {
      request.sendRequest({
        address: `customer/info/deleteSelectLogByCustomerId/${id}`,
        params: {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error('患者' + resp.msg )
					getHistoryList()
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error('患者' + resp.msg )

        },
        method: "POST",
      })
    }
    const PersonId = ref()
    // 去挂号
    const handleToRegister = (id: number) => {
      console.log('执行', id)
      PersonId.value = id
      isADD.value = 'register'
			title.value = "挂号"
      showDrawer.value = true
    }


    const screen = () => {
      console.log('点击了')
      search.dialogVisible = true
    }

    const close = () => {
      search.dialogVisible = false
    }

    const getPerson = (val: string) => {
      search.isActive = val
    }

    const getSeeDoctor = (val: string) => {
      search.isActive = val
    }

      // 新建预约部分
    const showDrawer = ref(false)
    const title = ref('新建预约')
    const isADD = ref('')
    // 打开新建预约
    const saveMakeAnAppointment = () => {
      isADD.value = 'makeanapp'
			title.value = "新建预约"
    }

    const saveAndRegister = () => {
			isADD.value = 'register'
			title.value = "挂号"
		}


    const handlebtn = () => {
      isADD.value = 'add'
			title.value = "个人信息"
    }
    const drawerClose = () => {
      ElMessageBox.confirm('此操作将关闭窗口, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
				showDrawer.value = false
			}).catch(() => {
					ElMessage({
						type: 'info',
						message: '已取消',
					});
      })
    }
    const cancel = () => {
      showDrawer.value = false
    }



    return {
      groupData,
      ...toRefs(search),
      ...toRefs(advancedSearch),
      hanledSearch,
      handleCurrentChange,
      handleSizeChange,
      handleGoDetails,

      goDetails,
      handleAppoint,
      PersonId,

      // btnData,
      btnData1,
      close,

      screen,
      getPerson,
      getSeeDoctor,

      getHistoryList,
      handleDelectItem,
      handleToRegister,
      historyList,

      // 预约
      showDrawer,
      title,
      isADD,
      saveMakeAnAppointment,
      saveAndRegister,
      handlebtn,
      drawerClose,
      cancel,
    }
  }
})
</script>

<style lang="scss" scoped>
.screen-body {
  border-top: 1px solid $mainColor;
  display: flex;
  height: 300px;
  .screen-left {
    border-right: 1px solid $mainColor;
    & > div {
      padding: 15px;
      cursor: pointer;
    }
  }
  .screen-right {
    padding: 10px;
    flex: 1;
    overflow-y: auto;
  }
}

.search-info {
  padding: 0 10px 10px 10px;
}

.pb {
  padding-bottom: 5px;
}
.f-a {
  display: flex;
  align-items: center
}

.flexwrap {
  display: flex;
  flex-wrap: wrap;
}

.allPatients {
  width: 100%;
  height: 100%;
  overflow: auto;
  // background: $a3-Color;
  box-sizing: border-box;
  display: flex;
  .allPatient-left-return {
    width: 15%;
    height: 100%;
    background: white;

    .patient-search {
      height: 45px;
      width: 100%;
      line-height: 45px;
      text-align: center;
      background: white;
      color: $mainColor;
      cursor: pointer;
      border-bottom: 1px solid #E4E7ED;
      box-sizing: border-box;

      & > i {
        padding-right: 5px;
        color: $mainColor;
      }
    }

    .person-item {
      display: flex;
      align-items: center;
      height: 45px;
      line-height: 45px;
      border-bottom: 1px solid #E4E7ED;
      cursor: pointer;
      position: relative;

      .avarat {
        height: 100%;
        & > span {
          margin: 2px;
          width: 40px;
          height: 40px;
        }
      }

      .icon {
        width: 32px;
        height: 32px;
        padding-left: 10px;
      }

      .person-name {
        padding: 0 10px;
      }
      & > span {

        & > a {
          text-decoration: none;
          color: $primaryText;
        }

        // & > a:link, a:active,
      }

      .p0 {
        padding: 0;
      }

      .delete-item {
        position: absolute;
        right: 0px;
        padding: 0 10px;
        display: none;
      }

      .register-item {
        position: absolute;
        right: 30px;
        display: none;
      }
    }
    .person-item:hover {
      border:1px solid $mainColor;
      background: white;
      color: $mainColor;

      & > .delete-item {
        display: block;
      }

      & > .register-item {
        display: block;
      }

      & > span > a {
        text-decoration: underline;
        color: $mainColor;
      }
    }
  }

  .allPatient-right-content {
    height: 100%;
    width: calc(100% - 15%);
  }


}

.item-active {
  background-color: #f5f6f7;
}
</style>
